const Router = require("koa-router");
const adminRouter = new Router();
const detailRouter = new Router();
const admin = require("../middleware/admin")();
const { sign } = require("jsonwebtoken");
global.secret = "imycode";
const jwt = require("koa-jwt")({ secret }); //jwt加密解密中间件
detailRouter.get("/info", async (ctx) => {
  ctx.body = {
    message: "这是info路由",
    username: ctx.state.user.username,
  };
});
adminRouter
  .post("/api/login", async (ctx, next) => {
    const user = ctx.request.body;
    //如果客户端有传过来,那我们签发令牌
    if (user && user.username) {
      let { username } = user;
      //token
      const token = sign({ username }, secret, { expiresIn: "1h" });
      ctx.body = {
        message: "得到了token",
        code: 1,
        token,
      };
    } else {
      ctx.body = {
        message: "参数错误",
        code: -1,
      };
    }
  })
  .get("/api/userInfo", jwt, async (ctx) => {
    ctx.body = {
      message: "token鉴权通过了",
      username: ctx.state.user.username,
    };
  })
  .get("/api/adminInfo", jwt, admin, async (ctx) => {
    ctx.body = {
      message: "welcome admin",
      username: ctx.state.user.username,
    };
  })
  .use("/api/user", jwt, admin, detailRouter.routes())
  .use(detailRouter.allowedMethods());

module.exports = {
  adminRouter,
};
